package com.atguigu.feilter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * LoginGlobalFilter
 *
 * @Author: 马伟奇
 * @CreateTime: 2021-03-05
 * @Description:
 *
 * 局部过滤器先执行，全局过滤器后执行，局部过滤器里面放的都是个性的东西，全局过滤器放到的都是共性东西
 */
@Component
public class LoginGlobalFilter implements GlobalFilter , Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("全局过滤器");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求参数 令牌 认证和授权
        String token = request.getQueryParams().getFirst("token");
        // 判断token是否有值
        if (StringUtils.isEmpty(token)){
            // 如果令牌为null，不允许登录，也就不允许进入到后台
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 认证没有通过
            return response.setComplete();
        }
        // 认证通过
        return chain.filter(exchange);
    }

    /**
     * 过滤器执行顺序，数字越小越先执行
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}